package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class LibraryShelf {

    private List<ShelfItem> items;
    private final String NEW_LINE = "\n";
    private final int NUMBERING_BEGIN = 1;
    private final int MINIMUM_INDEX = 0;


    public LibraryShelf() {
        items = new ArrayList<ShelfItem>();
    }

    public int size() {
        return items.size();
    }

    public LibraryShelf add(ShelfItem item) {
        items.add(item);
        return this;
    }

    public ShelfItem get(int index) {
        return isValidIndex(index) ? items.get(index) : null;
    }

    public boolean contains(ShelfItem shelfItem) {
        return items.contains(shelfItem);
    }

    public LibraryShelf remove(ShelfItem shelfItem) {
        items.remove(shelfItem);
        return this;
    }

    public ShelfItem getItemWithTitle(String title) {
        for (ShelfItem item : items) {
            if (item.getTitle().toLowerCase().equals(title.toLowerCase())) {
                return item;
            }
        }

        return null;
    }

    private boolean isValidIndex(int index) {
        return index >= MINIMUM_INDEX && index < this.size();
    }

    @Override
    public String toString() {
        Iterator<ShelfItem> iterator = items.iterator();
        String output = "";

        while (iterator.hasNext())
            output = output.concat(iterator.next().toString() + NEW_LINE);

        return output;
    }

}
